package com.woniuxy.litener;


import com.woniuxy.config.RabbitConfig;
import com.woniuxy.pojo.SysLogOpt;
import com.rabbitmq.client.Channel;
import com.woniuxy.service.LogFlushService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.amqp.support.AmqpHeaders;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.messaging.handler.annotation.Header;
import org.springframework.stereotype.Component;

import java.io.IOException;

@Component
@Slf4j
public class LogCacheListener {
    @Autowired
    private RedisTemplate<String, Object> redisTemplate;
    private static final String LOG_LIST_KEY = "log:list";

    private static final Long THRESHOLD = 10L;

    @Autowired
    private LogFlushService logFlushService; // 抽取的刷新逻辑


    /**
     * 监听缓存队列，接收日志对象，写入 Redis
     */
    @RabbitListener(queues = RabbitConfig.QUEUE_CACHE)
    public void saveToCache(SysLogOpt myLog, Channel channel,
                            @Header(AmqpHeaders.DELIVERY_TAG) Long tag,
                            Message message) throws IOException {
        try {
            if (myLog != null) {
                //使用redis list左边进入缓存
                redisTemplate.opsForList().leftPush(LOG_LIST_KEY,myLog);
                logFlushService.flushLogs();



                channel.basicAck(tag, false); // 正常确认
            }
        } catch (Exception e) {
            log.error("日志进入缓存失败，准备重试");
            //获取重投标记
            Boolean redelivered = message.getMessageProperties().getRedelivered();
            if (redelivered) {
                log.error("重试消费日志进入缓存失败，准备进如死信队列",e);

                channel.basicAck(tag,false);
            }else {
                log.error("重试消费日志进入缓存，重试一次");
                channel.basicNack(tag, false, true);
            }

        }
    }
}
